/*
*    l3qd - Light, light, lightweight queue
*    Copyright (C) 2024  Marcus Pedersén marcus@marcux.org
*
*    This program is free software: you can redistribute it and/or modify
*    it under the terms of the GNU General Public License as published by
*    the Free Software Foundation, either version 3 of the License, or
*    (at your option) any later version.
*
*    This program is distributed in the hope that it will be useful,
*    but WITHOUT ANY WARRANTY; without even the implied warranty of
*    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*    GNU General Public License for more details.
*
*    You should have received a copy of the GNU General Public License
*    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package show

import (
	"encoding/json"
	"fmt"
	"github.com/spf13/cobra"
	"notabug.org/marcux/l3q/internal/client"
	"notabug.org/marcux/l3q/internal/common"
	"os"
	"strconv"
)

var showTaskCmdFlagVerbose bool

var showTaskCmd = &cobra.Command{
	Use:   "task TASKID",
	Args:  cobra.ExactArgs(1),
	Short: "Shows information about specified task.",
	Long: `Description:
  Shows information about specified task.
  TASKID is required as a positional argument and is the id number of task to show.`,
	Run: func(cmd *cobra.Command, args []string) {
		taskid, err := strconv.Atoi(args[0])

		if err != nil {
			fmt.Fprintf(os.Stderr, "Failed to parse TASKID: %s, as integer.\nTASKID is required to be a positive integer.\nTry -h or --help for help.\n",
				args[0])

			if showTaskCmdFlagVerbose {
				fmt.Fprintf(os.Stderr, "%s\n", err)
			}

			os.Exit(1)
		}

		if taskid <= 0 {
			fmt.Fprintf(os.Stderr, "TASKID is required to be a positive integer.\nTry -h or --help for help.\n")
			os.Exit(1)
		}

		printTask(taskid)
	},
}

func printTask(taskid int) {
	tasks := []common.Task{}
	urlSuffix := fmt.Sprintf("/task?id=%d", taskid)

	jsonBytes := client.UrlGet(urlSuffix, showTaskCmdFlagVerbose)
	err := json.Unmarshal(jsonBytes, &tasks)
	if err != nil {
		if showTaskCmdFlagVerbose {
			fmt.Fprintf(os.Stderr, "Failed to decode json string to struct\n%s\n.", err)
		} else {
			fmt.Fprintf(os.Stderr, "Failed to decode json string.\n")
		}
		os.Exit(1)
	}

	if len(tasks) > 1 {
		fmt.Fprintf(os.Stderr, "Wrong response from daemon.\nMore than one task in response from l3qd daemon.")
		os.Exit(1)
	} else if len(tasks) == 0 {
		os.Exit(0)
	}

	t := tasks[0]

	nodename := ""

	if t.NodeID > 0 {
		nodes := []common.Node{}
		nodeUrlSuffix := fmt.Sprintf("/node?id=%d", t.NodeID)

		nodeJsonBytes := client.UrlGet(nodeUrlSuffix, showTaskCmdFlagVerbose)
		err := json.Unmarshal(nodeJsonBytes, &nodes)
		if err != nil {
			if showTaskCmdFlagVerbose {
				fmt.Fprintf(os.Stderr, "Failed to decode json string to struct\n%s\n.", err)
			} else {
				fmt.Fprintf(os.Stderr, "Failed to decode json string.\n")
			}
			os.Exit(1)
		}

		if len(nodes) > 1 {
			fmt.Fprintf(os.Stderr, "Wrong response from daemon.\nMore than one node in response from l3qd daemon.")
			os.Exit(1)
		}

		if len(nodes) == 1 {
			if len(nodes[0].Name) > 0 {
				nodename = nodes[0].Name
			} else {
				nodename = nodes[0].Hostname
			}
		}
	}

	memPeakHum := client.ScaleHuman(t.MemoryPeak)

	fmt.Printf("%-20s %d\n", "Taskid:", t.Id)
	fmt.Printf("%-20s %d\n", "SeqNo:", t.Seqno)

	if t.Cores > 0 {
		fmt.Printf("%-20s %d\n", "Cores:", t.Cores)
	}

	if len(nodename) > 0 {
		fmt.Printf("%-20s %s\n", "Node:", nodename)
	}
	fmt.Printf("%-20s %s\n", "Command:", t.Command)
	fmt.Printf("%-20s %s\n", "Working directory:", t.WorkDir)
	fmt.Printf("%-20s %s\n", "Unitname:", t.Unitname)
	fmt.Printf("%-20s %s\n", "Start time:", t.StartTime)
	fmt.Printf("%-20s %s\n", "End time:", t.EndTime)
	fmt.Printf("%-20s %s\n", "Run time:", t.RunTime)
	fmt.Printf("%-20s %d\n", "Mono start time:", t.MonoStartTime)
	fmt.Printf("%-20s %d\n", "Mono end time:", t.MonoEndTime)
	fmt.Printf("%-20s %s\n", "Active state:", t.ActiveState)
	fmt.Printf("%-20s %s\n", "Substate:", t.SubState)
	if len(t.EndTime) == 0 {
		fmt.Printf("%-20s %s\n", "Exit code:", "-")
	} else {
		fmt.Printf("%-20s %d\n", "Exit code:", t.ExitCode)
	}
	fmt.Printf("%-20s %d\n", "Main PID:", t.MainPid)
	fmt.Printf("%-20s %d (%s)\n", "Memory peak:", t.MemoryPeak, memPeakHum)
	fmt.Printf("%-20s %d\n", "PIDs peak:", t.PidsPeak)
	fmt.Println("")
	fmt.Println("Stdout:")
	fmt.Printf("%s\n", t.Stdout)
	fmt.Println("")
	fmt.Println("Stderr:")
	fmt.Printf("%s\n", t.Stderr)
	fmt.Println("")

}

func init() {
	showTaskCmd.Flags().BoolVarP(&showTaskCmdFlagVerbose, "verbose", "v", false, "Print verbose output")
}
